var utils = require('../../../utils/util.js')
var c = require('../../../utils/config.js')
Page({
    data: {
        imgurl: [
            '/static/images/Carousel.png',
            '/static/images/Carousel.png',
            '/static/images/Carousel.png',
            '/static/images/Carousel.png'
        ],
        num: 1,
        scrollTop: 0,
        commentData: [
            { title: '全部', num: 0, select: 0 },
            { title: '好评', num: 0, select: 1 },
            { title: '中评', num: 0, select: 2 },
            { title: '差评', num: 0, select: 3 },
        ],
        evaluationSelect: 0,
        star_rating: [
            '/static/images/star4.png',
            '/static/images/star4.png',
            '/static/images/star4.png',
            '/static/images/star4.png',
        ],
        Collection: false,
        hide: true,
        hide1: true,
        scroll_distance: '-660rpx',
        goodsId: 0,
        goodsPriceId: 0,
        type: 0,
        img_url: c.img_url,
        checkList: [],
        goodsInfo: [],
        evaluateList:[],
        grade:""

    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var goodsId = options.id;
        var s_openid = options.s_openid;
        this.setData({
            goodsId: goodsId
        });
        this.getGoodDetail();
        this.getEvaluateList();
        this.isShare(s_openid);
    },
    isShare:function(openid){//是否分享
        var scene = wx.getStorageSync("scene");
        openid = openid ? openid:"";
        wx.setStorageSync("s_openid", openid);
        utils.userthree(wx.getStorageSync("openId"));
    },
    getGoodDetail: function () {
        var goodsId = this.data.goodsId;
        var token = wx.getStorageSync("userinfo").wap_token;
        var type = this.data.type;
        var that = this;
        var data = {
            url: "/v1/goods/detail",
            page: 1,
            limit: 20,
            token: token,
            id: goodsId,
            type: type
        };
        utils.request(data).then(function (res) {
            if (res.code == 0) {
                var data = res.data;
                var checkList = [];
                for (var i in data.spec) {
                    var arr = [];
                    for (var j in data.spec[i].lists) {
                        if (j == 0) {
                            arr[j] = { checked: 1 };
                        } else {
                            arr[j] = { checked: 0 };
                        }
                    }
                    checkList[i] = arr;
                };
                //js 正则详情图片
                data['content_pic'] = [];
                data.content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                    data['content_pic'].push(c.img_url + capture);
                });
                
                if (data.iscollect == 1){
                    that.setData({
                        Collection:true
                    });
                }
                that.setData({
                    goodsInfo: data,
                    checkList: checkList
                });
                that.getGoodsPriceId();
            } else {

            }
        });
    },
    //数量减
    bindMinus: function () {
        var num = this.data.num;
        if (num == 1) {
            wx.showToast({
                title: '数量不能小于1',
                icon: 'none',
                duration: 2000
            })
        } else {
            this.setData({
                num: num - 1
            })
        }
    },
    //数量加
    bindPlus: function () {
        var num = parseInt(this.data.num);
        if (num >= this.data.goodsInfo.p_stock) {
            utils.errMsg("不能大于库存!");
            return false;
        }
        this.setData({
            num: num + 1
        })
    },
    changeSpec: function (e) {//选择规格
        var index = e.currentTarget.dataset.index;
        var i = e.currentTarget.dataset.i;
        var checkList = this.data.checkList;
        for (var k in checkList[index]) {
            checkList[index][k].checked = 0;
        }
        checkList[index][i].checked = 1;
        this.setData({
            checkList: checkList
        })
        this.getGoodsPriceId();

    },
    getGoodsPriceId: function () {//获取规格ID
        var checkList = this.data.checkList;
        var goodsSpec = this.data.goodsInfo.spec;
        var specName = "";
        for (var a in goodsSpec) {
            for (var b in goodsSpec[a].lists) {
                if (checkList[a][b].checked == 1) {
                    specName = specName + goodsSpec[a].lists[b].title + "_";
                }
            }
        }
        specName = specName.substr(0, specName.length - 1);
        var goodsId = this.data.goodsId;
        var goodsInfo = this.data.goodsInfo;
        var that = this;
        var data = {
            url: "/v1/goods/findgoods",
            goods_id: goodsId,
            title: specName
        };
        utils.request(data).then(function (res) {
            if (res.code == 0) {
                var data = res.data;
                goodsInfo.price = data.price;
                goodsInfo.p_stock = data.stock;
                that.setData({
                    goodsInfo: goodsInfo,
                    goodsPriceId: data.id
                })
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        });
    },
    getEvaluateList:function(){
        var goodsId = this.data.goodsId;
        var that = this;
        var grade = this.data.grade;
        var data = {
            url: "/v1/goodsevaluate/lists",
            goods_id: goodsId,
            page: 1,
            limit:20,
            grade: grade
        };
        utils.request(data).then(function (res) {
            if (res.code == 0) {
                var data = res.data;
                that.setData({
                    evaluateList:data
                })
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        });
    },
    addCart: function () {//添加购物车
        var goodsPriceId = this.data.goodsPriceId;
        if (!utils.checkLogin()){
            return false;
        }
        var nums = this.data.num;
        var token = wx.getStorageSync("userinfo").wap_token;
        if (goodsPriceId == 0) {
            goodsPriceId = this.data.goodsInfo.goods_price_id;
        }
        var that = this;
        var data = {
            url: "/v1/Ordercart/edit",
            goods_price_id: goodsPriceId,
            nums: nums,
            token: token
        };
        utils.request(data).then(function (res) {
            if (res.code == 0) {
                wx.showToast({
                    title: "添加成功",
                    icon: 'success',
                    duration: 2000
                })
                that.close();
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        });
    },
    confirmOrder: function () {//立即购买
        utils.checkLogin();
        var arr = [];
        var goodsInfo = this.data.goodsInfo;
        var goodsPriceId = this.data.goodsPriceId;
        var nums = this.data.num;
        var token = wx.getStorageSync("userinfo").wap_token;
        if (goodsPriceId == 0) {
            goodsPriceId = this.data.goodsInfo.goods_price_id;
        }
        arr[0] = { "title": goodsInfo.title, "nums": nums, "price": goodsInfo.price, id: goodsPriceId, pic: goodsInfo.pic };
        arr = JSON.stringify(arr);
        var goodsExt = { goods_type: goodsInfo.goods_type, totalNums: nums, totalMoney: goodsInfo.price * nums, totalPoint: goodsInfo.use_money_dj * nums  };
        goodsExt = JSON.stringify(goodsExt);
        if (arr.length == 0) {
            wx.showToast({
                title: '必须选择一件商品!',
                icon: "none"
            })
            return false;
        }
        this.close();
        wx.navigateTo({
            url: '/pages/shop/confirmorder/index?orderGoods=' + arr + "&goodsExt=" + goodsExt,
        })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        if (res.from === 'button') {
            // 来自页面内转发按钮
        }
        return {
            title: this.data.goodsInfo.title,
            path: '/pages/shop/goodsdetail/index?id=' + this.data.goodsId +"&s_openid="+wx.getStorageSync("openId"),
            success: function (res) {
                // 转发成功
            },
            fail: function (res) {
                // 转发失败
            }
        }
        var id = this.data.goodsInfo.id;
        var name = this.data.goodsInfo.title;
        var pic = c.img_url + this.data.goodsInfo.pic;
        return {
          title: name,
          path: '/pages/shop/goodsdetail/index?id=' + id + "&s_openid=" + wx.getStorageSync("openId"),
          imageUrl: pic,
          success: function (res) {
            wx.getSystemInfo({
              success: function (d) {
                var token = wx.getStorageSync("userinfo").wap_token;
                var data = {
                  url: "/v1/usershare/add",
                  token: token,
                  type: 0,
                  id: id
                };
                utils.request(data).then(function (res) {
                  if (res.code == 0) {

                  }
                });
              }
            })
          },
        }
    },
    chooseCatalog: function (e) {
        let key = e.currentTarget.dataset.select;
        if (key) {
            this.setData({
                scrollTop: 435
            })
        }
        this.setData({
            catalogSelect: key
        })
    },
    evaluationt: function (e) {
        let key = e.currentTarget.dataset.select;
        var grade = "";
        if(key == 1){//好评
            grade = "4,5";
        } else if (key == 2){
            grade = "3";
        } else if (key == 3){
            grade = "1,2";
        }
        this.setData({
            evaluationSelect: key,
            grade: grade
        })
        this.getEvaluateList();
    },
    Collection: function () {
        utils.checkLogin();
        var token = wx.getStorageSync("userinfo").wap_token;
        if (this.data.Collection){
            var data = {
                url: "/v1/collect/del",
                token: token,
                goods_id: this.data.goodsId
            };
            utils.request(data).then(function (res) {
                if (res.code == 0) {
                    wx.showToast({
                        title: '取消收藏成功',
                        icon: 'success',
                        duration: 2000
                    })
                } else {

                }
            });
        }else{
            var data = {
                url: "/v1/collect/add",
                token: token,
                goodsid: this.data.goodsId
            };
            utils.request(data).then(function (res) {
                if (res.code == 0) {
                    wx.showToast({
                        title: '收藏成功',
                        icon: 'success',
                        duration: 2000
                    })
                }
            });
        }
        
        this.setData({
            Collection: !this.data.Collection
        })
    },
    close: function () {
        this.setData({
            hide: true,
            hide1: true,
            scroll_distance: '-660rpx'
        })
    },
    add_cart: function () {
        this.setData({
            hide: false,
        });
        this.scroll_distance()
    },
    buy_btn: function () {
        this.setData({
            hide1: false,
        });
        this.scroll_distance()
    },
    scroll_distance: function () {
        this.setData({
            scroll_distance: 0
        })
    },
    openIndex: function () {
        wx.switchTab({
            url: '/pages/shop/index/index'
        })
    },
    //输入框
    editNums:function(e){
        if (e.detail.value >= this.data.goodsInfo.p_stock){
            //utils.errMsg("不能大于库存!");
            this.setData({
                num: this.data.goodsInfo.p_stock
            })
            return;
        }
        this.setData({
            num: e.detail.value
        })
    },
    openCart:function(){
        wx.switchTab({
            url: '/pages/shop/ordercart/index'
        })
    }
})
